package com.dudu.controller;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.dudu.bean.MenuBean;
import com.dudu.bean.ParamBean;
import com.dudu.bean.UserBean;
import com.dudu.enumeration.OperateTypeEnum;
import com.dudu.enumeration.StatusEnum;
import com.dudu.service.ILogService;
import com.dudu.service.IMenuService;
import com.dudu.service.IUserService;
import com.dudu.service.impl.LogService;
import com.dudu.service.impl.MenuServiceImpl;
import com.dudu.service.impl.UserServiceImpl;
import com.dudu.utils.DateUtils;
import com.dudu.utils.Encrypt;

import core.CoreService;
/**
 * 基础菜单+登录
 * @author gaoxs
 *
 */
public class MenuController extends CoreService implements IMenuController {
	//当前登陆用户
	private  final String KEY_CURRENT_USER = "key_current_user";
	//当前登陆用户类型
	private  final String KEY_CURRENT_USER_TYPE = "key_current_user_type";
	//菜单相关
	private IMenuService menuService=new MenuServiceImpl();
	//用户相关
	private IUserService userService=new UserServiceImpl();
	//用于记录相应接口调用的日志
	private ILogService logService = new LogService();
	/**
	 * 登录
	 * @return
	 */
	public String doLogin() {
		//登录账号
		String account = this.getRequest().getParameter("account");
		//登录密码
		String password = this.getRequest().getParameter("password");
		//登录IP
		String ipAddr = this.getRequest().getRemoteAddr();

		JSONObject json = new JSONObject();
		if(StringUtils.isBlank(account)){
			json.put("retFlag", false);
			json.put("retMsg", "请输入用户名");
		}else if(StringUtils.isBlank(password)){
			json.put("retFlag", false);
			json.put("retMsg", "请输入密码");
		}else{
			//根据登录账号查询用户对象
			UserBean user = this.userService.getUserByAccount(account);
			if(user == null){
				json.put("retFlag", false);
				json.put("retMsg", "用户名输入有误，请确认");
			}else{
				//查看用户对象是否为启用状态
				if(StatusEnum.ON.getKey().equals(user.getStatus())){
					String uPassword = user.getPassword();
					//判断密码是否正确
					if(Encrypt.md5Encrypt(password).equals(uPassword)){
						user.setIp(ipAddr);//登录IP
						user.setLast_login_time(user.getLogin_time());
						user.setLogin_time(DateUtils.getCurrentTime());
						userService.updateLastLoginTime(user);//更新最后一次登录时间
						//设置返回值
						JSONObject resultObj = new JSONObject();
						resultObj.put("account", user.getAccount());
						resultObj.put("id", user.getId());
						resultObj.put("name", user.getName());
						resultObj.put("type", user.getType());//用户类型：系统用户、ISV用户
						
						this.getSession().setAttribute(this.KEY_CURRENT_USER, user);
						this.getSession().setAttribute(this.KEY_CURRENT_USER_TYPE, user.getType());
						
						json.put("redirecturl", "business/index.html");
						json.put("userInfo",resultObj);
						json.put("retFlag", true);
						json.put("retMsg", "登陆成功");
						
						logService.log(OperateTypeEnum.LOGIN.getKey(), user.getId(), user.getName(), 
								"t_user", "登陆时间："+user.getLogin_time()+"|登陆IP："+user.getIp());
					}else{
						json.put("retFlag", false);
						json.put("retMsg", "密码输入有误，请确认");
					}
				}else{
					json.put("retFlag", false);
					json.put("retMsg", "该账号已停用");
				}
			}
		}
		
		return returnData(json.toString());
	}
	/**
	 * 获取用户
	 * @return
	 */
	public String getUser() {
		// 最后返回的对象
		JSONObject json = new JSONObject();
		// 获取当前登录用户信息
		UserBean currentUser = (UserBean) this.getSession().getAttribute(KEY_CURRENT_USER);
		// 判断如果用户信息不为空则继续下一步		
		if(currentUser == null){
			json.put("retFlag", false);
			json.put("retMsg", "请登陆");
			json.put("redirecturl", "index.html");
		}else{
			JSONObject resultObj = new JSONObject();
			resultObj.put("userAccout", currentUser.getAccount());
			resultObj.put("userId", currentUser.getId());
			resultObj.put("userName", currentUser.getName());
			resultObj.put("lastLoginTime", currentUser.getLast_login_time());
			resultObj.put("type", currentUser.getType());//用户类型：系统用户、ISV用户
			
			json.put("retFlag", true);
			json.put("userInfo", resultObj);
			json.put("retMsg", null);
		}
		return returnData(json.toString());
	}

	/**
	 * 登录退出
	 * @return
	 */
	public String doLogout(){
		// 最后返回的对象
		JSONObject json = new JSONObject();
		// 获取当前登录用户信息
		UserBean currentUser = (UserBean) this.getSession().getAttribute(KEY_CURRENT_USER);
		// 判断如果用户信息不为空则继续下一步
		if(currentUser == null){
			json.put("retFlag", false);
			json.put("retMsg", "error");
			json.put("redirecturl", "");
		}else{
			this.getSession().removeAttribute(KEY_CURRENT_USER);
			
			json.put("retFlag", true);
			json.put("userInfo", "success");
			json.put("retMsg", "");
		}
		return returnData(json.toString());
	}
	/**
	 * 获取登录者的菜单
	 * @return
	 */
	public String getMenu() {
		// 最后返回的对象
		JSONObject json = new JSONObject();
		// 获取当前登录用户信息
		UserBean currentUser = (UserBean) this.getSession().getAttribute(KEY_CURRENT_USER);
		// 判断如果用户信息不为空则继续下一步
		if(currentUser == null){
			json.put("retFlag", false);
			json.put("retMsg", "请登陆");
			json.put("redirecturl", "/index.html");
		}else{
			//获取用户ID
			int userId = Integer.valueOf(this.getRequest().getParameter("userId"));
			//根据用户ID查询其能查看的权限
			String menuString = menuService.getUserMenu(userId);
			json.put("list", menuString);
		}
		return returnData(json.toString());
	}
	/**
	 * 修改密码
	 * @return
	 */
	@Override
	public String changePwd(){
		// 最后返回的对象
		JSONObject json = new JSONObject();
		// 获取当前登录用户信息
		UserBean currentUser = (UserBean) this.getSession().getAttribute(KEY_CURRENT_USER);
		// 判断如果用户信息不为空则继续下一步
		if(currentUser == null){
			json.put("retFlag", false);
			json.put("retMsg", "请登陆");
			json.put("redirecturl", "/index.html");
		}else{
			String dataStr = (String) this.getRequest().getParameter("data");//获取data
			JSONObject data = JSONObject.fromObject(dataStr);//转成JSON
			String oldpwd = data.getString("oldpwd");//旧密码
			String pwd = data.getString("pwd");//新密码
			String checkpwd = data.getString("checkpwd");//确认密码
            //判断旧密码是否正确
			if(currentUser.getPassword().equals(Encrypt.md5Encrypt(oldpwd))) {	
	            //判断新密码与确认密码是否一致
				if(pwd.equals(checkpwd)) {
	            	currentUser.setPassword(Encrypt.md5Encrypt(pwd));//设置新密码
	            	//更新密码
		            int result = userService.updatePwd(currentUser);
					if(result != -1){
						json.put("retFlag", true);
						json.put("retMsg", "密码修改成功");
					}else{
						json.put("retFlag", true);
						json.put("retMsg", "密码修改失败");
					}
	            }else{
	            	json.put("retFlag", false);
	            	json.put("retMsg", "新密码和重复密码不一致");
	            }	            
            } else {
            	json.put("retFlag", false);
            	json.put("retMsg", "原密码不正确");
            }
		}
		return returnData(json.toString());
	}
	/**
	 * 菜单列表
	 * @return
	 */
	public String queryAll() {
		// 最后返回的对象
		JSONObject object = new JSONObject();
		// 获取当前登录用户信息
		UserBean currentUser = (UserBean) this.getSession().getAttribute(KEY_CURRENT_USER);
		// 判断如果用户信息不为空则继续下一步
        if (currentUser != null) {
        	JSONArray jsonArray = new JSONArray();
        	//查询所有菜单
	        List<JSONObject> menus = this.menuService.queryAll();
	        jsonArray = JSONArray.fromObject(menus);
	        
	        JSONObject dataobject = new JSONObject();
	        object.put("flag", "000000");
	        object.put("desc", "success");
	        dataobject.put("totalItemNum", menus.size());
	        dataobject.put("items", jsonArray);
	        object.put("data", dataobject);
        } else {
			object.put("flag", "100000");
		}
        return returnData(object.toString());
	}
	
	/**
	 * 增加菜单
	 * @return
	 */
	public String doInsert() {
		// 最后返回的对象
		JSONObject object = new JSONObject();
		// 获取当前登录用户信息
		UserBean currentUser = (UserBean) this.getSession().getAttribute(KEY_CURRENT_USER);
		// 判断如果用户信息不为空则继续下一步
        if (currentUser != null) {
            String dataStr = (String) this.getRequest().getParameter("data");
            JSONObject data = JSONObject.fromObject(dataStr);
            String name = data.getString("name");
            String url = data.getString("url");
            int parentId = data.getInt("parentId");
            String isleaf = data.getString("isleaf");
            String sort = data.getString("sort"); 
            String icon = data.getString("icon"); 
            int treelevel = data.getInt("treelevel"); 

            MenuBean menu = new MenuBean();
            menu.setIcon(icon);//图标
            menu.setIs_leaf(isleaf);//
            menu.setName(name);
            menu.setParent_id(parentId);
            menu.setSort(sort);
            menu.setTree_level(treelevel);
            menu.setUrl(url);
            
            int pId = this.menuService.insertMenu( menu);//新增菜单
            
            logService.log(OperateTypeEnum.ADD.getKey(), currentUser.getId(), currentUser.getName(), 
					"t_menu", "名称："+name+"|地址："+url+
					"|父节点："+parentId+"|树层："+treelevel+
					"|树叶："+isleaf+"|序号："+sort+
					"|图标："+icon+"||主键："+ pId);
            
            object.put("flag", "000000");
	        object.put("desc", "success");
        } else {
			object.put("flag", "100000");
		}

        return returnData(object.toString());
    }
	
	/**
	 * 修改菜单
	 * @return
	 */
	public String doEdit() {
		// 最后返回的对象
		JSONObject object = new JSONObject();
		// 获取当前登录用户信息
		UserBean currentUser = (UserBean) this.getSession().getAttribute(KEY_CURRENT_USER);
		// 判断如果用户信息不为空则继续下一步
        if (currentUser != null) {
            String dataStr = (String) this.getRequest().getParameter("data");
            JSONObject data = JSONObject.fromObject(dataStr);
            String menuid = data.getString("menuid");
            String name = data.getString("name");
            String url = data.getString("url");
            int parentId = data.getInt("parentId");
            String isleaf = data.getString("isleaf");
            String sort = data.getString("sort"); 
            String icon = data.getString("icon"); 
            int treelevel = data.getInt("treelevel"); 

            if (StringUtils.isNotBlank(menuid)) {
                MenuBean menu = new MenuBean();
                menu.setId(Integer.valueOf(menuid));
                menu.setIcon(icon);
                menu.setIs_leaf(isleaf);
                menu.setName(name);
                menu.setParent_id(parentId);
                menu.setSort(sort);
                menu.setTree_level(treelevel);
                menu.setUrl(url);
                int pId = this.menuService.updateMenu( menu);
                
                logService.log(OperateTypeEnum.EDIT.getKey(), currentUser.getId(), currentUser.getName(), 
    					"t_menu", "名称："+name+"|地址："+url+
    					"|父节点："+parentId+"|树层："+treelevel+
    					"|树叶："+isleaf+"|序号："+sort+
    					"|图标："+icon+"||主键："+ pId);
            }
            object.put("flag", "000000");
	        object.put("desc", "success");
        } else {
			object.put("flag", "100000");
		}

        return returnData(object.toString());
	}
	/**
	 * 菜单
	 * @return
	 */
	public String menuName() {
		// 最后返回的对象
		JSONArray jsonArray = new JSONArray();
		// 获取当前登录用户信息
		UserBean currentUser = (UserBean) this.getSession().getAttribute(KEY_CURRENT_USER);
		// 判断如果用户信息不为空则继续下一步
        if (currentUser != null) {
        	//获取菜单级别
        	int level = Integer.valueOf(this.getRequest().getParameter("level"));
    		//根据菜单级别查询所有菜单
    		List<ParamBean> menus = menuService.queryMenuName(level);
    		if(menus != null){
    			ParamBean bean = new ParamBean();
    			bean.setId("-1");
    			bean.setText("根节点");
    			menus.add(bean);
    			jsonArray = JSONArray.fromObject(menus);
    		}
        }
		return returnData( jsonArray.toString() );
	}
}
